<?php

class FormRecover extends CFormModel {

    public $username_email;
    public $user;
    public $captcha;
    public $config = array();

    public function init() {
        $this->config = array(
            'class' => 'form',
            'elements' => array(
                'username_email' => array('type' => 'text'),
                'captcha' => array('type' => 'MyCaptcha', 'clickableImage' => true, 'showRefreshButton' => false)
            ),
            'buttons' => array(
                'recover' => array('type' => 'htmlSubmit', 'value' => 1, 'class' => 'blue', 'label' => '<span class="label">Вспомнить все!</span>'),
                'registration' => array('type' => 'link', "class" => "right_alight", 'label' => 'Регистрация', 'href' => Y::url("user/registration")),
                'login' => array('type' => 'link', "class" => "right_alight", 'label' => 'Вход', 'href' => Y::url("user/login")),
            )
        );
        return parent::init();
    }

    public function rules() {
        return array(
            array('username_email', 'required'),
            array('captcha', 'captcha', 'allowEmpty' => !extension_loaded('gd')),
            array('username_email', 'checkUE'),
        );
    }

    public function attributeLabels() {
        return array(
            'username_email' => 'E-Mail',
            'captcha' => 'Капча'
        );
    }

    public function checkUE($attribute, $params) {
        $this->user = User::model()->find("LOWER(email) =?", array(strtolower($this->username_email)));
        if(!$this->user) {
            $this->addError('username_email', 'Этого пользователя нет в системе');
            return false;
        }
        if(!$this->hasErrors()) {
            $this->user->code = User::encrypt(microtime());
            $this->user->save();
            $email = Yii::app()->email;
            $email->to = $this->user->email;
            $email->from = Yii::app()->params['adminEmail'];
            $email->message = Yii::app()->controller->renderPartial('../email/recover', array('model' => $this->user), true);
            $email->subject = 'Востановление пароля.';
            $email->send();
        }
        return true;
    }
}
